package com.adminserver.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.adminserver.customEntity.SaltEntity;
import com.adminserver.entity.AdminEntity;
import com.adminserver.entity.RepairOrdersEntity;
import com.adminserver.entity.RepairTypeEntity;
import com.adminserver.mapper.RepairOrdersMapper;
import com.adminserver.service.AdminService;
import com.adminserver.service.RepairOrdersService;
import com.adminserver.service.RepairTypeService;
import com.adminserver.util.DateGenerator.DateGenerator;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.adminserver.util.rsaUtil.GenerateKey;
import com.adminserver.util.rsaUtil.RsaUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/home")
public class HomeController {

    @Autowired
    RepairOrdersService repairOrdersService;

    @Autowired
    RepairOrdersMapper repairOrdersMapper;

    @Autowired
    RepairTypeService repairTypeService;

    @Autowired
        RsaUtil rsaUtil;

    @Autowired
    AdminService adminService;

    @Autowired
    SaltEntity saltEntity;




    @GetMapping("repairAmountQuery")
    public ResponseUtil repairAmountQuery() {
        // 本月报修量、上月报修量、本年报修量、上年报修量
        HashMap<String, Object> result = new HashMap<>();
        LambdaQueryWrapper<RepairOrdersEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        String[] yearInMonthBeginEndTime = DateGenerator.getYearInMonthBeginEndTime(DateUtil.date().year(), DateUtil.date().month());
        // 本月
        lambdaQueryWrapper.between(RepairOrdersEntity::getRepairDate,
                yearInMonthBeginEndTime[0],
                yearInMonthBeginEndTime[1]);
        int count = repairOrdersService.count(lambdaQueryWrapper);
        result.put("currentMonths", count);

        yearInMonthBeginEndTime = DateGenerator.getYearInMonthBeginEndTime(DateUtil.date().year(), DateUtil.date().offset(DateField.MONTH, -1).month());
        // 上月
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.between(RepairOrdersEntity::getRepairDate,
                DateUtil.beginOfMonth(DateUtil.offsetMonth(new Date(), -1)),
                DateUtil.endOfMonth(DateUtil.offsetMonth(new Date(), -1)));
        count = repairOrdersService.count(lambdaQueryWrapper);
        result.put("lastMonths", count);

        // 某年的开始结束时间生成器
        String[] yearBeginEndTime = DateGenerator.getYearBeginEndTime(DateUtil.date().year());

        // 本年
        lambdaQueryWrapper.clear();
        lambdaQueryWrapper.between(RepairOrdersEntity::getRepairDate,
                yearBeginEndTime[0],
                yearBeginEndTime[1]);
        count = repairOrdersService.count(lambdaQueryWrapper);
        result.put("currentYear", count);

        // 上年
        lambdaQueryWrapper.clear();
        yearBeginEndTime = DateGenerator.getYearBeginEndTime(DateUtil.date().offset(DateField.YEAR, -1).year());
        lambdaQueryWrapper.between(RepairOrdersEntity::getRepairDate,
                yearBeginEndTime[0],
                yearBeginEndTime[1]);
        count = repairOrdersService.count(lambdaQueryWrapper);
        result.put("lastYear", count);

        return ResponseUtil.setE(ResponseEnum.OK).setData(result);
    }

    @GetMapping("/annualRepairStatist")
    public ResponseUtil annualRepairStatist(@RequestParam int year) {
        String[] yearBeginEndTime = DateGenerator.getYearBeginEndTime(year);
        return ResponseUtil.setE(ResponseEnum.OK).setData(repairOrdersMapper.queryAnnualRepairStatist(yearBeginEndTime[0], yearBeginEndTime[1]));
    }

    @GetMapping("/annualRepairTrend")
    public ResponseUtil annualRepairTrend(@RequestParam int year) {
        String[] beginEndTime = DateGenerator.getYearBeginEndTime(year);
        List<Map<String, Object>> mapList = repairOrdersMapper.queryAnnualRepairTrend(beginEndTime[0], beginEndTime[1]);

        List<RepairTypeEntity> typeValues = repairTypeService.list();

        DateFormat df = DateFormat.getDateInstance();
        Calendar calendar = Calendar.getInstance();

        HashMap<String, int[]> map = new HashMap<>();
        typeValues.forEach(key -> {
            int[] months = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            mapList.forEach(item -> {
                String typeValue = item.get("typeValue").toString();
                if (typeValue.equals(key.getTypeValue())) {
                    String repairData = item.get("repairData").toString();
                    Date parse = null;
                    try {
                        parse = df.parse(repairData);
                        calendar.setTime(parse);
                        int month = calendar.get(Calendar.MONTH);
                        months[month]++;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
            map.put(key.getTypeValue(), months);
        });
        return ResponseUtil.setE(ResponseEnum.OK).setData(map);
    }

    @PostMapping("/updatePass")
    public ResponseUtil updatePass(@RequestBody String encryptPass){
        try{
            String decrypt = rsaUtil.RsaPriDecrypt(encryptPass, GenerateKey.cacheKey.get(GenerateKey.PUBLIC), GenerateKey.cacheKey.get(GenerateKey.PRIVATE));
            HashMap<String, String> hashMap = JSONObject.parseObject(decrypt, HashMap.class);

            String oldPass = DigestUtil.md5Hex(hashMap.get("oldPass").concat(saltEntity.getPassword()));
            String newPass = DigestUtil.md5Hex(hashMap.get("newPass1").concat(saltEntity.getPassword()));
            String account = StpUtil.getLoginId().toString();

            AdminEntity adminEntity = adminService.getById(account);
            if (ObjectUtil.isEmpty(adminEntity)) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("账号不存在");

            if (!adminEntity.getPassword().equals(oldPass)) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("原密码错误");
            AdminEntity entity = new AdminEntity();
            entity.setAccount(account);
            entity.setPassword(newPass);
            adminService.updateById(entity);
        }catch (Exception e){
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("密码修改失败，请刷新页面后重试");
        }
        StpUtil.logout();
        return ResponseUtil.setE(ResponseEnum.OK).setMsg("密码更新成功，请重新登录");
    }
}

